﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Jzy.Workflow.Node;
using System.Data;
using System.Drawing;
using System.Web;
using Jzy.Workflow.Line;

namespace Jzy.Workflow.GDI
{
    public class Flow
    {
        private List<FlowLine> _lines;
        private List<FlowNode> _nodes;

        private int _flowID;

        public Flow(int flowID)
        {
            _flowID = flowID;
        }

        public void Display()
        {
            FlowNodeBO nodeBO = new FlowNodeBO();
            FlowLineBO lineBO = new FlowLineBO();

            List<FlowNodeInfo> dtNode = nodeBO.GetList(_flowID);
            foreach (FlowNodeInfo dr in dtNode)
            {
                FlowNode node = new FlowNode();
                node.PKID = dr.ID;
                node.Name = dr.Name;
                node.Top = dr.Top;
                node.Width = dr.Width;
                node.Left = dr.Left;
                node.Height = dr.Height;
                node.Type = (FlowNodeType)dr.TypeID;

                _nodes.Add(node);
              
            }

            List<FlowLineInfo> dtLine = lineBO.GetList(_flowID);

            foreach (FlowLineInfo dr in dtLine)
            {
                FlowLine line = new FlowLine();
                line.PKID = dr.ID;
                line.LineType = (Jzy.Workflow.Line.LineType)dr.TypeID;
                foreach (FlowNode node in _nodes)
                {
                    if (dr.FromNodeID == node.PKID)
                    {
                        line.FromNode = node;
                    }
                    if (dr.ToNodeID == node.PKID)
                    {
                        line.ToNode = node;
                    }
                }

                _lines.Add(line);
            }

            RenderFlow();
        }

        private void RenderFlow()
        {
            double width = 0;
            double height = 0;
            foreach (FlowNode node in _nodes)
            {
               
                if (width < (node.Left + node.Width))
                {
                    width = node.Left + node.Width;
                }

                if (height < (node.Top + node.Height))
                {
                    height = node.Top + node.Height;
                }
            }

            Bitmap image = new Bitmap((int)width, (int)height);

            foreach (FlowLine line in _lines)
            {
                line.Draw(image);
            }

            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);

            HttpResponse Response = System.Web.HttpContext.Current.Response;

            Response.ClearContent();
            Response.ContentType = "image/Jpeg";
            Response.BinaryWrite(ms.ToArray());
        }
    }
}
